/*
3-22-11 Added modal linkTable popup
3-11-11 Changed jqUploader to allow for .MP4 files
12-27-10		refactoring of updateCoords() >>> .parent().parent().....
7-26-10 moved jQuery function to bottom of the doc >> IE6 should play better
		cleaned up comments
		added colorPicker installation for margoV - only coded for single-instance. works with unique id (#colorPicker), not class		
7-24-09 onClose, datepicker will set the "age" input value to the age in months from today > for R.E.A.D. (ESS)
7-23-09 altered the datepicker binding function to handle multiple instances (ESS)

*/

//generates the hex-digits for a colour.
jQuery.hex = function (x) {
	hexDigits = new Array("0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F");
	return isNaN(x) ? "00" : hexDigits[(x - x % 16) / 16] + hexDigits[x % 16];
};

 //Function to get hex format a rgb colour
jQuery.rgb2hex = function (rgb) {
	return $.hex(rgb[0]) + $.hex(rgb[1]) + $.hex(rgb[2]);
};

function jcrop_target(my_id) {
    return function(c) { updateCoords(my_id,c); };
};

function updateCoords(my_id,c)
{
	var croppableImg = $("#" + my_id);
	// my_id =  "*_croppable"
	croppableImg.find('.x').val(c.x);
	croppableImg.find('.y').val(c.y);
	croppableImg.find('.w').val(c.w);
	croppableImg.find('.h').val(c.h);
	
	var fullImgContainer = croppableImg.parent().parent();
	var cropContainer = fullImgContainer.parent();
	var thisCropBox = cropContainer.find(".cropbox");
	var dimensionVarPrefix = fullImgContainer.attr("id"); 

	var previewWidth = $("input[id='"+dimensionVarPrefix + "_width']").val();
	var previewHeight = $("input[id='"+dimensionVarPrefix + "_height']").val();
	fullImgContainer.find('.response').html("width : " + previewWidth + " // height : " + previewHeight);
	previewBoxWidth = previewWidth;
	previewBoxheight = previewHeight;
	var rx = previewBoxWidth / c.w;
	var ry = previewBoxheight / c.h;


	var originalImgPath = thisCropBox.attr('src');
	//$("#" + my_id).find('.response').html("original image path : " + originalImgPath);
	cropContainer.find(".preview").attr({src: originalImgPath});
	imgWidth = thisCropBox.width();
	imgHeight = thisCropBox.height();
	newWidth = Math.round(rx * imgWidth);
	newHeight = Math.round(ry * imgHeight);
	//$("#" + my_id).find('.response').html("previewWidth : " + previewWidth);
	cropContainer.find(".previewBox").css("border","3px solid red");	
	cropContainer.find(".jCropSubmit").css("display","block");
	cropContainer.find(".jCropSubmit").html("CLICK TO CROP");
	$("#saveRecord").attr("disabled",true);
	
	cropContainer.find(".preview").css({
		width: Math.round(rx * imgWidth) + 'px',
		height: Math.round(ry * imgHeight) + 'px',
		marginLeft: '-' + Math.round(rx * c.x) + 'px',
		marginTop: '-' + Math.round(ry * c.y) + 'px'
	});

};

function checkCoords() {
	if (parseInt($('#x').val())) return true;
	alert('Please select a crop region then press submit.');
	return false;
};

function linkedTableActions() {

	$(".removeBtn").live('click', function() {
		clickedBtn = $(this);
		linkedTableName = findParentByClass(clickedBtn, "linkedTable").attr("id");
		child_id = findParentByClass(clickedBtn, "backListRecord").attr("id");
		
		//log(linkedTableName + "//" +child_id);
		$.ajax({
			url: "ajax.php",
			data: "linkedTableName="+linkedTableName+"&child_id="+child_id+"&parent_id="+parent_id+"&AJAXtask=linkedTableRemove",
			cache: false,
			success: function(msg){
				//alert(msg);
				findParentByClass(clickedBtn, "backListRecord").fadeOut();
			}
		}); //end ajax
	
	});
}

function autocompleteBind(currentLinkTable,currentChildTableName,currentChildFieldName) {
	$(this).autocomplete('ajax.php', {
		matchContains: true,
		extraParams : {
			'child_tablename':currentChildTableName,
			'child_fieldname':currentChildFieldName,
			'link_tablename':currentLinkTable,
			'parent_tablename':parent_table,
			'parent_recordID': parent_id,
		},
		minChars: 0
	});
}

$(function() {
	setMinWidth();

//$.setBehaviors();
	linkedTableActions();
//jQuery.setBehaviors = function () {
	//$('.cropbox').after("<div class='response'>RESPONSE</div>");
	
	$(".hasdatepicker").each(function () {
		altFieldId = $(this).parent().attr("id") + "_datestore";
		$(this).datepicker({
				altField: '#'+altFieldId,
				altFormat: 'yy-mm-dd',
				onClose: function(dateText, inst) {
					var dateArray = dateText.split("/");
					var monthOfBirth = parseInt(dateArray[0],10);
					var dayOfBirth = parseInt(dateArray[1],10);
					var yearOfBirth = parseInt(dateArray[2],10);
					var curDate = new Date();
					var curYear = curDate.getFullYear();
					var curMonth = curDate.getMonth() + 1;
					var age = ((curYear*12) + curMonth) - ((yearOfBirth*12) + monthOfBirth);
					$("#age").val(age);
				}
		});
	})
	.blur( function () {
		var nameStem = $(this).closest('.date').attr('id'),
				datestore = $("#"+nameStem+"_datestore"),
				currVal = $(this).val(),
				splitDate = currVal.split('/'),
				m = splitDate[0],
				d = splitDate[1],
				y = splitDate[2],
				formattedDate = y+"-"+m+"-"+d;
		datestore.val(formattedDate);
	});
	
	//$('.hastimepicker').timepickr();
	$('.hastimepicker').timepicker({
		ampm: true,
		stepMinute : 15
	});
	
	$('.previewBox').after("<div class='jCropSubmit'>CLICK TO CROP</div>");
	//$("input[name='']").val();
	
	$('.previewBox').each(function () {
		var dimensionVarPrefix = $(this).parent().prev().prev().prev().attr("id");
		//alert("dimensionVarPrefix : " + dimensionVarPrefix);
		var previewWidth = $("input[id='"+dimensionVarPrefix + "_width']").val();
		var previewHeight = $("input[id='"+dimensionVarPrefix + "_height']").val();
		var aspectRatio = previewWidth/previewHeight;
		//alert("width : " + previewWidth + "\nheight : " + previewHeight + "\nratio : " + aspectRatio);
		//alert (previewWidth + " // " + previewHeight);


		$(this).css({width: previewWidth,height: previewHeight});
	});

	$('.cropbox').each(function () {
		var ancestorClass = $(this).parent().parent().parent().attr('class');
		//alert(ancestorClass);
		if (ancestorClass != 'noCrop') {
			var myId = $(this).parent().attr('id');
			var dimensionVarPrefix = $(this).parent().parent().parent().attr('id');
			var previewWidth = $("input[id='"+dimensionVarPrefix + "_width']").val();
			var previewHeight = $("input[id='"+dimensionVarPrefix + "_height']").val();
			var aspectRatio = previewWidth/previewHeight;
			//alert("dimensionVarPrefix : " + dimensionVarPrefix);
			//alert("width : " + previewWidth + "\nheight : " + previewHeight + "\nratio : " + aspectRatio);
			$(this).Jcrop({
				aspectRatio: aspectRatio,
				onSelect: jcrop_target(myId),
				onChange: jcrop_target(myId),
				boxHeight: 350
			});
			$('.preview').each(function () {
				var thumbImg = $("#" + myId).parent().parent().parent().find(".preview");
				if (!thumbImg.attr("src")) {
					newThumbImg = $("#" +myId +' .cropbox').attr('src');
					thumbImg.attr({src: newThumbImg})
				};
			}); //end .preview function
		}
	});
	
	$(".groupItem .saveGroupItem").click(function () {
		var inputString = "";
		
		$(this).parent().find('.formElement').each(function () {
			var inputName = $(this).attr("name");
			var inputValue = $(this).attr("value");
			inputString += inputName+"="+inputValue+"&";
		});
		
		$.ajax({
			url: "ajax.php",
			data: inputString+"AJAXtask=saveGroupItem&child_tablename="+child_tablename,
			cache: false,
			success: function(thumbFilePath){
				$.ajax({
					url: child_tableName+"_groupwrite.php",
					cache: false,
					success: function(groupItemHTML){
						$(this).parent().parent().html(groupItemHTML);	
					}
				}); //end interior ajax function
			}
		}); //end exterior ajax function
	}); // end (".groupItem .saveGroupItem").click(function () 
	$(".groupItem .saveNewGroupItem").click(function () {
		var inputString = "";
		thisItem = $(this);
		
		$(this).parent().find('.formElement').each(function () {
			var inputName = $(this).attr("name");
			var inputValue = $(this).attr("value");
			inputString += inputName+"="+inputValue+"&";
		});
		
		$.ajax({
			url: "ajax.php",
			data: inputString+"AJAXtask=saveNewGroupItem&child_tablename="+child_tablename,
			cache: false,
			success: function(html){
				//alert(html);
				thisItem.after("<div class='deleteGroupItem'>DELETE ITEM</div>");
				thisItem.next().after("<div id='saveResponse'>Entry added!</div>");
					//####### SOME SORT OF RECURSIVE FUNCTION TO REBIND THE ACTIONS
				$.ajax({
					url: child_tableName+"_groupwrite.php",
					data: "addNew=true",
					cache: false,
					success: function(groupItemHTML){
						alert("groupItemHTML : \n" + groupItemHTML);
						//alert("parent class : " + thisVar.parent().parent().attr("class"));
						thisItem.parent().after(groupItemHTML);	
					}
				}); //end interior ajax function
			}
		}); //end exterior ajax function
	}); // end (".groupItem .saveNewGroupItem").click(function () 
	
	$(".groupItem .deleteGroupItem").click(function () {
		thisItem = $(this)
		var inputString = "";
		
		
		$(this).parent().find('.formElement').each(function () {
			var inputName = $(this).attr("name");
			var inputValue = $(this).attr("value");
			inputString += inputName+"="+inputValue+"&";
		});
		deletionId = $(this).parent().find(".flash-replaced").attr("id");
		alert(deletionId);
		$.deleteAllFiles(deletionId);
		$.ajax({
			url: "ajax.php",
			data: inputString+"AJAXtask=deleteGroupItem&child_tablename="+child_tablename,
			cache: false,
			success: function(html){
				alert(html);
				thisItem.prev().remove();
				thisItem.html('Deleting..');
				//thisItem.parent().css({background: "red"});
				thisItem.parent().fadeOut('slow');
			}
		}); //end exterior ajax function
	}); // end (".groupItem .deleteNewGroupItem").click(function () 

	
	$('.jCropSubmit').click(function () {
		var currGranddaddy = $(this).parent().parent();
		var xCoord = currGranddaddy.find('.x').val();
		var yCoord = currGranddaddy.find('.y').val();
		var width = currGranddaddy.find('.w').val();
		var height = currGranddaddy.find('.h').val();
		var fileName = currGranddaddy.find('.cropbox').attr("src");

		var dimensionVarPrefix = currGranddaddy.find('.fileUploadCrop').attr('id');
		var targetWidth = $("input[id='"+dimensionVarPrefix + "_width']").val();
		var targetHeight = $("input[id='"+dimensionVarPrefix + "_height']").val();
		
		$(this).html("CROPPING...");

		//alert("xCoord: " + xCoord + "\nfileName: " + fileName);
		 
		currentThis = $(this);
		
		$.ajax({
			url: "ajax.php",
			data: "xCoord="+xCoord+"&yCoord="+yCoord+"&width="+width+"&height="+height+"&fileName="+fileName+"&targetWidth="+targetWidth+"&targetHeight="+targetHeight+"&AJAXtask=crop",
			cache: false,
			success: function(thumbFilePath){
				//alert(thumbFilePath);
				currentThis.next().val(thumbFilePath);
				currentThis.html("SUCCESS!");
				currentThis.fadeOut("slow"); //('display','none');
				$("#saveRecord").removeAttr("disabled");
				currentThis.parent().find('.previewBox').css("border-color",$("body").css("background-color"));
			}
		});
		return false;
	});
	$(".dropDown_related").each(function() {
		$(this).addClass("populated");	
		var parent_field = $(this).attr("name");
		var child_tablename = eval(parent_field + "_child_tablename");
		var child_fieldname = eval(parent_field + "_child_fieldname");
		var currentValue = $(this).find("option").val();
		var id = $("input[name='id']").attr("value");
		//alert("child_table // " + child_tablename +"\nchild_fieldname" + child_fieldname);
		$.ajax({
			url: "ajax.php",
			data: "id="+id+"&field="+parent_field+"&child_tablename="+child_tablename+"&child_fieldname="+child_fieldname+"&currentValue="+currentValue+"&AJAXtask=populateDropDown",
			cache: false,
			success: function(dropDownHTML){
				//alert(dropDownHTML);
				$("select[name='"+parent_field+"']").html(dropDownHTML);
			}
		});
	}); //end dropdown_related
	
	var hiddenInput;
	var fieldName;
	$("#cancelRecord").click(	function() {
		window.location = refererURL;
	});
	
	$("#saveRecord").click(	function() {
		if ( $("#ageGroupsForm").length ) {
			if ($("select[name='ageUnit'] option:selected").val() == "Years" ) { var multiplier = 12;}
			else {var multiplier = 1;}
			var minAge = $("input[name='minAge']").val();
			var maxAge = $("input[name='maxAge']").val();
			$("input[name='minAgeMonths']").val(minAge * multiplier);
			$("input[name='maxAgeMonths']").val(maxAge * multiplier);
		}
	}); //end saveRecord.click()
	
	$(".saveGroupItem").click(	function() {
		$(".date").each(function (i) {
			var year,month,day,hour,minute,second;
			var fieldName = $(this).attr("id");
			$(this).find("input").each(function () {
				var className = $(this).attr("class");
				var value = $(this).val();
				switch (className) {
					case "formElement year":
						year = value;
						break;
					case "formElement month":
						month = value;
						break;
					case "formElement day":
						day = value;
						break;
					case "formElement hour":
						hour = value;
						break;
					case "formElement minute":
						minute = value;
						break;
					case "formElement second":
						second = value;
						break;
					default:
						break;
				}
			});
			hiddenInput = year + "-" + month + "-" + day;
			if (hour || minute || second) {
				hiddenInput += " " + hour + ":" + minute + ":" + second;		
			}
			var hiddenInputHTML;
			hiddenInputHTML = "<input type='hidden' name='"+fieldName+"' value='"+hiddenInput+"' />";
			$(this).after(hiddenInputHTML);
			
		});
		
		//return false;
	}); //end saveGroupItem.click()
	
	$(".dropDown_related_addBtn").click(function() {
		$(this).css({display: "none"});
		var currentParent = $(this).parent().find('select').attr('name');
		var child_tablename = eval(currentParent + "_child_tablename");
		var child_fieldname = eval(currentParent + "_child_fieldname");
		//alert(currentParent);
		$(this).parent().find('select').css({display: "none"});
		var newOptField = "<div class='newOptField'><input type='text' name='"+child_fieldname+"' class='newOpt'/>"+
							"<a class='saveNewOpt positiveBtns'>SAVE OPTION</a>"+
							"<a class='cancelNewOpt negativeBtns'>CANCEL</a>"+
							"</div>";
		$(this).after(newOptField);
		currentThis = $(this);
		/*
$(".saveNewOpt, .cancelNewOpt").hover(
			function () {
				$(this).css({background: "#5F5E50"});
			}, 
			function () {
				$(this).css({background: "#8F8E79"});
			}
		);
*/
		$(".cancelNewOpt").click(function() {
			currentThis.parent().find('select').css({display: "block"});
			currentThis.parent().find('.newOpt').val('');
			currentThis.parent().find('.newOptField').css({display: "none"});
			currentThis.css({display: "block"});
		});
		$(".saveNewOpt").click(function() {
			var currentValue = $(this).parent().find('.newOpt').val();
			//alert("child_table // " + child_tablename +"\nchild_fieldname" + child_fieldname);
			$.ajax({
				url: "ajax.php",
				data: "child_tablename="+child_tablename+"&child_fieldname="+child_fieldname+"&currentValue="+currentValue+"&AJAXtask=saveNewOpt",
				cache: false,
				success: function(newOptID){
					var newOptHTML = "<option selected='selected'  value='" + newOptID + "'>" + currentValue + "</option>";
					currentThis.parent().find('select').css({display: "block"});
					currentThis.parent().find("option:last").after(newOptHTML);
					currentThis.parent().find('.newOpt').val('');
					currentThis.parent().find('.newOptField').css({display: "none"});
					currentThis.css({display: "block"});
				}
			});
		});
		//return false;
	}); //end dropDown_related_addBtn.click()



	var bgColor = $("body").css("background-color");
	var colorArray = [];
	bgColor = bgColor.substr(4,13);
	colorArray = bgColor.split(", ");		
	bgColor = $.rgb2hex(colorArray);
		
	$('.fileUpload').jqUploader({
		background:bgColor,
		barColor:'000000',
		allowedExt:'*.avi; *.jpg; *.jpeg; *.png; *.gif; *.mov; *.mp4; *.mp3; *.flv; *.pdf',
		allowedExtDescr: 'what you want',
		validFileMessage: 'Thanks, now hit Upload!',
		endMessage: 'Success! To upload again, hit Browse',
		hideSubmit: false,
		uploadScript: 'flash_upload.php?jqUploader=1',
		afterScript: 'none'
	});

$(".autocompleteSearchBox").click(function() {
	$(this).val(''); 
	$(this).css({
		'font-style':'normal',
		'color':'black'
		}); 
});
/*
$("#io_colorPicker").ColorPicker({flat: true});
if (typeof currentHexValue !== 'undefined') {
	//console.log("currentHexValue = " + currentHexValue);
	$('#io_colorPicker').ColorPickerSetColor(currentHexValue);
}
*/

//};//end document.onReady function
});
